#!/bin/bash
source include_bench.sh
result_wcet_alloc="./log/result_wcet_alloc"
result_wcet_free="./log/result_wcet_free"
result_wcet_rss="./log/result_wcet_rss"
 
do_bench_wcet() {
	echo "LD_PRELOAD=$1 $2 $3"
	${NICE} ${PERF} env LD_PRELOAD=$1 $2 $3 1> ./log/wcet.tsv 2> ./log/wcet_rss.tsv
	rss=`cat ./log/wcet_rss.tsv | grep "Maximum resident set size" | grep "[0-9]\+" -o`
	usrtime=`cat ./log/wcet_rss.tsv | grep "User time" | grep "[0-9]\+.[0-9]\+" -o`
	systime=`cat ./log/wcet_rss.tsv | grep "System time" | grep "[0-9]\+.[0-9]\+" -o`
	minorfault=`cat ./log/wcet_rss.tsv | grep "Minor (reclaiming a frame) page faults" | grep "[0-9]\+" -o`

	cat ./log/wcet.tsv
	percen_alloc=`cat ./log/wcet.tsv | tail -n2 | head -n1`
	percen_free=`cat ./log/wcet.tsv | tail -n1`

	echo "$4 ${percen_alloc}" >> ${result_wcet_alloc}.tsv
	echo "$4 ${percen_free}" >> ${result_wcet_free}.tsv
	echo "$4 ${rss} ${usrtime} ${systime} ${minorfault}" >> ${result_wcet_rss}.tsv
	sleep 1
}

# backup 
mv ${result_wcet_alloc}.tsv ${result_wcet_alloc}_bak.tsv
mv ${result_wcet_free}.tsv ${result_wcet_free}_bak.tsv
mv ${result_wcet_rss}.tsv ${result_wcet_rss}_bak.tsv



${curpath}/build/gtest_wcet.o 1> ./log/wcet.tsv 2> ./log/wcet_rss.tsv
hd=`cat ./log/wcet.tsv | head -n1`
echo "lib ${hd}" > ${result_wcet_alloc}.tsv
echo "lib ${hd}" > ${result_wcet_free}.tsv
echo "lib rss usr sys pagefault" > ${result_wcet_rss}.tsv



trap "exit" INT
echo "run ${1} x 2 times (gcc + clang)" 
for ((i=1;i<=${1};i++))
do
	echo "start benchmarking...."
	libpath=${ldlibpaths}
	for lib in ${liblist}   
	do
		cur_libpath=`echo "${libpath}" | head -n 1`
		libpath=`echo "${libpath}" | tail -n +2`
		# echo ${cur_libpath}
		do_bench_wcet ${cur_libpath} ${lddir} ${curpath}/build/gtest_wcet.o ${lib}
		do_bench_wcet ${cur_libpath} ${lddir} ${curpath}/build/cltest_wcet.o ${lib}
	done
done
